package gu.sql2java.geometry.fastjson;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * JTS几何对象FASTJSON序列化反序列化实现<br>
 * 参见 <a href="https://www.osgeo.org/projects/jts/">JTS Topology Suite</a>
 * @author guyadong
 *
 * @param <T>
 * @since 3.18.0
 */
public class GeometryCodec<T extends Geometry> implements ObjectSerializer, ObjectDeserializer {
    
    /**
     * 将geometry类型序列化为WKT JSON字符串
     */
    @SuppressWarnings("unchecked")
    @Override
    public void write(JSONSerializer jsonSerializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        T geom = (T) object;
        jsonSerializer.write(geom.toString());
    }

    /**
     * 将WKT字符串反序列为{@link Geometry}
     */
    @SuppressWarnings("unchecked")
    @Override
    public T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        Object value = parser.parse();
        if (value == null) {
            return null;
        } else {
            String wkt = (String) value;
            WKTReader reader = new WKTReader();
            try {
                return (T) reader.read(wkt);
            } catch (ParseException e) {
                throw new JSONException(e.getMessage(),e);
            }
        }
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }
}
